<script setup>
import { onMounted, ref } from 'vue';
import { List, Cell, Button,showSuccessToast, showFailToast } from 'vant';
import {getProcessDefinitionPage,onlineProcessDefinition,offlineProcessDefinition} from '@/api/dolphin.js';
import { useRoute } from 'vue-router';

const items = ref([]);
const loading = ref(false);
const finished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const searchVal = ref('');

const router = useRoute();
// 从路由参数中获取 clusterId 和 projectCode
const clusterId = ref(router.params.clusterId || 'default-cluster-id');
const projectCode = ref(Number(router.params.projectCode) || 12345); // 确保转换为数字类型

const showFailureStrategyPicker = ref(false);
const showPriorityPicker = ref(false);
const showWarningTypePicker = ref(false);
const showExecTypePicker = ref(false);
const showTaskDependTypePicker = ref(false);
const showRunModePicker = ref(false);
// 初始化搜索结果
onMounted(() => {
  onSearch();
});

const onSearch = async () => {
  try {
    // 重置分页和加载状态
    console.log('开始搜索');
    currentPage.value = 1;
    items.value = [];
    loading.value = true;
    finished.value = false;

    const response = await getProcessDefinitionPage(clusterId.value, projectCode.value, currentPage.value, pageSize.value, searchVal.value);
    
    items.value.push(...(response.records || []));
    
    // 如果返回的结果少于请求的数量，则认为已经没有更多数据了
    if (response.totalPages <= response.currentPage) {
      finished.value = true;
    }

    loading.value = false;
    console.log('搜索完成', { items: items.value, finished: finished.value });
    console.log('currentPage.value:',{ currentPage:currentPage.value });
  } catch (error) {
    console.error('搜索工作流定义失败:', error);
    loading.value = false;
  }
};

const onCancel = () => {
  searchVal.value = '';
  // 清除搜索结果并重置状态
  items.value = [];
  loading.value = false;
  finished.value = false;
};



const onLoad = async () => {
  if (finished.value) return; // 如果已经完成加载，则不执行加载更多

  loading.value = true;

  try {
    console.log('开始加载更多');
    currentPage.value++;
    const response = await getProcessDefinitionPage(clusterId.value, projectCode.value, currentPage.value, pageSize.value, searchVal.value);
    items.value.push(...(response.records || []));
    console.log('加载更多完成', { items: items.value, finished: finished.value });
    console.log('currentPage.value:',{ currentPage:currentPage.value });
    // 当加载的数据达到总数量时，设置 finished 为 true
    if (response.totalPages <= response.currentPage) {
      finished.value = true;
    }
  } catch (error) {
    console.error('加载更多项目失败:', error);
  } finally {
    loading.value = false;
    console.log('加载更多完成', { items: items.value, finished: finished.value });
  }
};

// 截断文本并添加省略号
function truncateText(text, maxLength = 25) {
  return text.length > maxLength ? `${text.slice(0, maxLength)}...` : text;
}
// 下线
async function offline(item) {
  try {
    // 等待下线操作完成
    await offlineProcessDefinition(clusterId.value, projectCode.value, item.code);

    // 下线成功后重新搜索以刷新列表
    onSearch();
    
    // 可选: 显示成功的消息给用户
    showSuccessToast('下线成功');
  } catch (error) {
    // 处理错误情况
    console.error('下线失败:', error);
    // 可选: 显示错误信息给用户
    showFailToast('下线失败，请重试');
  }
}

// 上线
async function online(item) {
  try {
    // 等待下线操作完成
    await onlineProcessDefinition(clusterId.value, projectCode.value, item.code);

    // 下线成功后重新搜索以刷新列表
    onSearch();
    
    // 可选: 显示成功的消息给用户
    showSuccessToast('上线成功');
  } catch (error) {
    // 处理错误情况
    console.error('上线失败:', error);
    // 可选: 显示错误信息给用户
    showFailToast('上线失败，请重试');
  }
}



// 弹出层相关的状态管理
const showStartDialog = ref(false);
const currentItem = ref(null);
const startForm = ref({
  failureStrategy: 'CONTINUE',
  failureStrategyText: '继续执行',
  processInstancePriority: 'MEDIUM',
  priorityText: '中',
  warningType: 'NONE',
  warningTypeText: '不通知',
  execType: 'PARALLEL',
  execTypeText: '并行',
  taskDependType: 'TASK_POST',
  taskDependTypeText: '任务后置',
  runMode: 'RUN_MODE_SERIAL',
  runModeText: '串行模式',
  warningGroupId: 0,
  startNodeList: '',
  processDefinitionCode: '',
  scheduleTime: '',
  environmentCode: '',
  startParams: '',
  expectedParallelismNumber: '',
  workerGroup: 'default',
  dryRun: 0
});

// 添加表单配置选项
const failureStrategyOptions = [
  { text: '继续执行', value: 'CONTINUE' },
  { text: '结束执行', value: 'END' }
];

const priorityOptions = [
  { text: '最高', value: 'HIGHEST' },
  { text: '高', value: 'HIGH' },
  { text: '中', value: 'MEDIUM' },
  { text: '低', value: 'LOW' },
  { text: '最低', value: 'LOWEST' }
];

const warningTypeOptions = [
  { text: '不通知', value: 'NONE' },
  { text: '成功通知', value: 'SUCCESS' },
  { text: '失败通知', value: 'FAILURE' },
  { text: '全部通知', value: 'ALL' }
];

const execTypeOptions = [
  { text: '并行', value: 'PARALLEL' },
  { text: '串行', value: 'SERIAL' }
];

const taskDependTypeOptions = [
  { text: '任务前置', value: 'TASK_PRE' },
  { text: '任务后置', value: 'TASK_POST' }
];

const runModeOptions = [
  { text: '串行模式', value: 'RUN_MODE_SERIAL' },
  { text: '并行模式', value: 'RUN_MODE_PARALLEL' }
];

// 添加表单显示值
const formDisplay = ref({
  failureStrategy: '',
  processInstancePriority: '',
  warningType: '',
  execType: '',
  taskDependType: '',
  runMode: ''
});

// 修改 getOptionText 辅助函数
const getOptionText = (options, value) => {
  const option = options.find(item => item.value === value);
  return option ? option.text : '';
};

// 修改选择器确认事件处理
const handlePickerConfirm = (type, value) => {
  switch(type) {
    case 'failureStrategy':
      startForm.value.failureStrategy = value.value;
      startForm.value.failureStrategyText = value.text;
      showFailureStrategyPicker.value = false;
      items.value = [...items.value];
      break;
    case 'priority':
      startForm.value.processInstancePriority = value.value;
      startForm.value.priorityText = value.text;
      showPriorityPicker.value = false;
      items.value = [...items.value];
      break;
    case 'warningType':
      startForm.value.warningType = value.value;
      startForm.value.warningTypeText = value.text;
      showWarningTypePicker.value = false;
      items.value = [...items.value];
      break;
    case 'execType':
      startForm.value.execType = value.value;
      startForm.value.execTypeText = value.text;
      showExecTypePicker.value = false;
      items.value = [...items.value];
      break;
    case 'taskDependType':
      startForm.value.taskDependType = value.value;
      startForm.value.taskDependTypeText = value.text;
      showTaskDependTypePicker.value = false;
      items.value = [...items.value];
      break;
    case 'runMode':
      startForm.value.runMode = value.value;
      startForm.value.runModeText = value.text;
      showRunModePicker.value = false;
      items.value = [...items.value];
      break;
  }
};

// 修改 onStart 方法，确保初始化时设置正确的显示文本
const onStart = (item) => {
  currentItem.value = item;
  // 保持现有的值，但更新 processDefinitionCode
  startForm.value = {
    ...startForm.value,
    processDefinitionCode: item.code,
    // 设置初始显示文本
    failureStrategyText: getOptionText(failureStrategyOptions, startForm.value.failureStrategy),
    priorityText: getOptionText(priorityOptions, startForm.value.processInstancePriority),
    warningTypeText: getOptionText(warningTypeOptions, startForm.value.warningType),
    execTypeText: getOptionText(execTypeOptions, startForm.value.execType),
    taskDependTypeText: getOptionText(taskDependTypeOptions, startForm.value.taskDependType),
    runModeText: getOptionText(runModeOptions, startForm.value.runMode)
  };
  
  showStartDialog.value = true;
};

// 确认启动工作流实例
const onConfirmStart = async () => {
  try {
    // 创建一个新对象，只包含需要提交的字段
    const submitParams = {
      processDefinitionCode: currentItem.value.code,
      failureStrategy: startForm.value.failureStrategy,
      processInstancePriority: startForm.value.processInstancePriority,
      warningType: startForm.value.warningType,
      warningGroupId: startForm.value.warningGroupId,
      execType: startForm.value.execType,
      startNodeList: startForm.value.startNodeList,
      taskDependType: startForm.value.taskDependType,
      runMode: startForm.value.runMode,
      scheduleTime: startForm.value.scheduleTime,
      environmentCode: startForm.value.environmentCode,
      startParams: startForm.value.startParams,
      expectedParallelismNumber: startForm.value.expectedParallelismNumber,
      workerGroup: startForm.value.workerGroup,
      dryRun: startForm.value.dryRun
    };
    
    await startProcessInstance(clusterId.value, projectCode.value, submitParams);
    showSuccessToast('启动成功');
    showStartDialog.value = false;
    
    // 刷新列表
    onSearch();
  } catch (error) {
    console.error('启动工作流实例失败:', error);
    showFailToast('启动失败');
  }
};

// 启动工作流实例方法
const handleStartInstance = async () => {
  try {
    const clusterId = clusterStore.currentCluster?.id;
    const projectCode = route.params.projectCode;
    
    await startProcessInstance(clusterId, projectCode, startForm.value);
    showSuccessToast('启动成功');
    showStartDialog.value = false;
    await loadProcessList(); // 刷新列表
  } catch (error) {
    showFailToast(error.message);
  }
};

// 添加状态显示相关方法
const getStateText = (state) => {
  switch (state) {
    case 'ONLINE':
      return '在线';
    case 'OFFLINE':
      return '下线';
    default:
      return state;
  }
};

const getStateClass = (state) => {
  switch (state) {
    case 'ONLINE':
      return 'state-running';
    case 'OFFLINE':
      return 'state-stopped';
    default:
      return 'state-default';
  }
};

</script>

<template>
    <van-search
      v-model="searchVal"
      placeholder="工作流名称"
      show-action
      @search="onSearch"
      @cancel="onCancel"/>
    <van-list v-model:loading="loading" :finished="finished" @load="onLoad" :offset="100" finished-text="没有更多了">
      <van-cell 
      v-for="(item) in items"
      :key="item.id"
      :title="truncateText(item.name)"
      style="height: 60px;">
        <template #label>
          <span :class="getStateClass(item.releaseState)">
            {{ getStateText(item.releaseState) }}
          </span>
        </template>

        <template #right-icon>
          <van-button 
            round 
            class="button-with-space" 
            type="success" 
            size="small" 
            icon="play-circle-o" 
            v-if="item.releaseState==='ONLINE'" 
            @click="onStart(item)">
          </van-button>
          <van-button round class="button-with-space" color="#EBEAEA" size="small" icon="play-circle-o" v-else></van-button>
          <van-button round class="button-with-space" type="danger" size="small" icon="down"  v-if="item.releaseState==='ONLINE'" @click="offline(item)"></van-button>
          <van-button round class="button-with-space" type="warning" size="small" icon="back-top"  v-else @click="online(item)"></van-button>
          <van-button round class="button-with-space" type="primary" size="small" icon="clock-o"></van-button>
          <van-button round class="button-with-space" type="primary" size="small" icon="calendar-o"></van-button>
        </template>
      </van-cell>
    </van-list>

    <!-- 添加启动工作流实例的弹出层 -->
    <van-popup v-model:show="showStartDialog" position="bottom" :style="{ height: '70%' }">
      <div class="popup-content">
        <div class="popup-header">
          <h3>启动工作流实例</h3>
        </div>
        
        <van-form @submit="onConfirmStart">
          <!-- 失败策略 -->
          <van-cell 
            is-link 
            title="失败策略" 
            :value="startForm.failureStrategyText"
            @click="showFailureStrategyPicker = true"
          />

          <!-- 实例优先级 -->
          <van-cell 
            is-link 
            title="实例优先级" 
            :value="startForm.priorityText"
            @click="showPriorityPicker = true"
          />

          <!-- 告警类型 -->
          <van-cell 
            is-link 
            title="告警类型" 
            :value="startForm.warningTypeText"
            @click="showWarningTypePicker = true"
          />

          <!-- 执行类型 -->
          <van-cell 
            is-link 
            title="执行类型" 
            :value="startForm.execTypeText"
            @click="showExecTypePicker = true"
          />

          <!-- 任务依赖类型 -->
          <van-cell 
            is-link 
            title="任务依赖类型" 
            :value="startForm.taskDependTypeText"
            @click="showTaskDependTypePicker = true"
          />

          <!-- 运行模式 -->
          <van-cell 
            is-link 
            title="运行模式" 
            :value="startForm.runModeText"
            @click="showRunModePicker = true"
          />

          <!-- Worker分组 -->
          <van-field
            v-model="startForm.workerGroup"
            name="workerGroup"
            label="Worker分组"
            placeholder="请输入Worker分组"
          />

          <!-- 环境名称 -->
          <van-field
            v-model="startForm.environmentCode"
            name="environmentCode"
            label="环境名称"
            placeholder="请输入环境名称"
          />

          <!-- 补数开关 -->
          <van-cell title="补数">
            <template #right-icon>
              <van-switch v-model="startForm.dryRun" :active-value="1" :inactive-value="0" />
            </template>
          </van-cell>

          <!-- 启动参数 -->
          <van-field
            v-model="startForm.startParams"
            name="startParams"
            label="启动参数"
            type="textarea"
            rows="3"
            placeholder="请输入启动参数(JSON格式)"
          />

          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
              运行
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <!-- Picker 弹出层 -->
    <van-popup v-model:show="showFailureStrategyPicker" position="bottom">
      <van-picker
        show-toolbar
        title="选择失败策略"
        :columns="failureStrategyOptions"
        @confirm="(value) => handlePickerConfirm('failureStrategy', value)"
        @cancel="showFailureStrategyPicker = false"
      />
    </van-popup>

    <van-popup v-model:show="showPriorityPicker" position="bottom" :overlay="true">
      <van-picker
        show-toolbar
        title="选择实例优先级"
        :columns="priorityOptions"
        @confirm="(value) => handlePickerConfirm('priority', value)"
        @cancel="showPriorityPicker = false"
      />
    </van-popup>

    <van-popup v-model:show="showWarningTypePicker" position="bottom" :overlay="true">
      <van-picker
        show-toolbar
        title="选择告警类型"
        :columns="warningTypeOptions"
        @confirm="(value) => handlePickerConfirm('warningType', value)"
        @cancel="showWarningTypePicker = false"
      />
    </van-popup>

    <van-popup v-model:show="showExecTypePicker" position="bottom" :overlay="true">
      <van-picker
        show-toolbar
        title="选择执行类型"
        :columns="execTypeOptions"
        @confirm="(value) => handlePickerConfirm('execType', value)"
        @cancel="showExecTypePicker = false"
      />
    </van-popup>

    <van-popup v-model:show="showTaskDependTypePicker" position="bottom" :overlay="true">
      <van-picker
        show-toolbar
        title="选择任务依赖类型"
        :columns="taskDependTypeOptions"
        @confirm="(value) => handlePickerConfirm('taskDependType', value)"
        @cancel="showTaskDependTypePicker = false"
      />
    </van-popup>

    <van-popup v-model:show="showRunModePicker" position="bottom" :overlay="true">
      <van-picker
        show-toolbar
        title="选择运行模式"
        :columns="runModeOptions"
        @confirm="(value) => handlePickerConfirm('runMode', value)"
        @cancel="showRunModePicker = false"
      />
    </van-popup>
  </template>

<style scoped>
.button-with-space {
  margin-right: 1px; /* 设置右侧间距 */
}

.popup-content {
  padding: 16px;
}

.popup-header {
  text-align: center;
  margin-bottom: 20px;
}

.popup-header h3 {
  margin: 0;
  font-size: 18px;
  color: #323233;
}

/* 添加右侧文本的样式 */
:deep(.van-cell__value) {
  color: #969799;
  flex: none;
  text-align: right;
}

/* 添加状态颜色样式 */
.state-running { 
  color: #409eff;  /* 在线-蓝色 */
}
.state-stopped { 
  color: #909399;  /* 下线-灰色 */
}
.state-default { 
  color: #606266;  /* 默认-深灰色 */
}

</style>
